import { extend, trim } from "lodash";
import React from "react";
import PropTypes from "prop-types";
import { useDebouncedCallback } from "use-debounce";
import { Section, Input, Select, TextArea, ContextHelp } from "@/components/visualizations/editor";
import { formatSimpleTemplate } from "@/lib/value-format";

function Editor({ column, onChange }) {
  return (
    <React.Fragment>
      <Section>
        <Select
          label="显示样式"
          defaultValue={column.selectDisplay || ''}
          onChange={value => onChange({ selectDisplay: value })}
        >
          <Select.Option value="">下拉选择</Select.Option>
          <Select.Option value="option">按钮选择</Select.Option>
          <Select.Option value="button">开关选择</Select.Option>
        </Select>
      </Section>
      <Section>
        <TextArea
          label={
            <React.Fragment>
              待选择值
              <ContextHelp.EnumFormatSpecs />
            </React.Fragment>
          }
          rows={3}
          value={column.enumOptions}
          onChange={e => onChange({ enumOptions: e.target.value })}
        />
      </Section>
      <Section>
        <Input
          label={
            <React.Fragment>
              默认值
              <ContextHelp.FunctionFormatSpecs />
            </React.Fragment>
          }
          defaultValue={column.defaultValue}
          onChange={event => onChange({ defaultValue: event.target.value })}
        />
      </Section>
    </React.Fragment>
  );
}

Editor.propTypes = {
  column: PropTypes.shape({
    name: PropTypes.string.isRequired,
    linkUrlTemplate: PropTypes.string,
    linkTextTemplate: PropTypes.string,
    linkTitleTemplate: PropTypes.string,
    linkOpenInNewTab: PropTypes.bool,
  }).isRequired,
  onChange: PropTypes.func.isRequired,
};

export default function initEnumColumn(column) {
  function prepareData(row) {
    row = extend({ "@": row[column.name] }, row);

    const href = trim(formatSimpleTemplate(column.linkUrlTemplate, row));
    if (href === "") {
      return {};
    }

    const title = trim(formatSimpleTemplate(column.linkTitleTemplate, row));
    const text = trim(formatSimpleTemplate(column.linkTextTemplate, row));

    const result = {
      href,
      text: text !== "" ? text : href,
    };

    if (title !== "") {
      result.title = title;
    }
    if (column.linkOpenInNewTab) {
      result.target = "_blank";
    }

    return result;
  }

  function LinkColumn({ row }) {
    // eslint-disable-line react/prop-types
    const { text, ...props } = prepareData(row);
    return <a {...props}>{text}</a>;
  }

  LinkColumn.prepareData = prepareData;

  return LinkColumn;
}

initEnumColumn.friendlyName = "选择";
initEnumColumn.Editor = Editor;
